<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use \PHPExcel;
use \PHPExcel_IOFactory;
use \Lang2;
use Log;

class PageController extends Controller{

	public function pageLogin(Request $request){
		return view('towers.login', [
            'data' => ''
        ]);
	}

    public function pageTicketMgmr(Request $request){
        $currentUser = \MyUtils::getCurrentUser($request);
        $tickets = \MyDB::getInstance()->findAll("select * from tickets order by id desc", []);

        foreach ($tickets as &$ticket){
            $reply = $ticket['reply'];
            $replies = json_decode($reply, true);
            $ticket['reply'] = count($replies) == 0 ? '' : $replies[0]['content'];

            $anonymous = $ticket['anonymous'];
            if($anonymous == 0){
                $ticket['anonymous'] = '非匿名';
            }else{
                $ticket['anonymous'] = '匿名';
            }
        }

//        PageController::writeExcel(".", "feedback_" . time(), $tickets, [
//            '唯一标识' => 'id',
//            '内容' => 'content',
//            '回复' => 'reply',
//        ]);
//        echo '<pre><code>' . json_encode($tickets, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT) . '</code></pre>';

        return view('towers.ticket_mgmr', [
            'tickets' => $tickets,
            'sid' => $currentUser['sid'],
        ]);
    }

    public function addBr($str, $interval){
	    
    }

    public function pageExport(Request $request){
        $currentUser = \MyUtils::getCurrentUser($request);


        $department = $request->input("department", 1);
        $type = $request->input("type", 1);

        $sql = "select * from tickets where 1 = 1 "; //" order by id desc";

        if($department != 1){
            $sql .= " and department = '$department' ";
        }
        if($type != 1){
            $sql .= " and type = '$type' ";
        }

        $sql .= " order by id desc";

        $tickets = \MyDB::getInstance()->findAll($sql, []);

        foreach ($tickets as &$ticket){
            $reply = $ticket['reply'];
            $replies = json_decode($reply, true);
            $ticket['reply'] = count($replies) == 0 ? '' : $replies[0]['content'];

            $anonymous = $ticket['anonymous'];
            if($anonymous == 0){
                $ticket['anonymous'] = '非匿名';
            }else{
                $ticket['anonymous'] = '匿名';
            }
        }

        $filename = "feedback_" . time();
        PageController::writeExcel(".", "feedback_" . time(), $tickets, [
            '唯一标识' => 'id',
            '内容' => 'content',
            '回复' => 'reply',
            '部门' => 'department',
            '类型' => 'type',
            '是否匿名' => 'anonymous',
            '联系人' => 'contactor',
            '电话' => 'phone',
        ]);

        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Accept-Length:". filesize("./$filename.xlsx"));
        header("Content-Disposition: attachment; filename=$filename.xlsx");

        return file_get_contents("./$filename.xlsx");
    }

    public function pageImport(Request $request){
        $currentUser = \MyUtils::getCurrentUser($request);

        $file = $request->file('file');
        if($file == null || !$file->isValid()){
            return "无效文件";
        }
//        $allowed_extensions = ["xls", "xlsx"];
//        if ($file->getClientOriginalExtension() && !in_array($file->getClientOriginalExtension(), $allowed_extensions)) {
//            return "你只能上传excel";
//        }
        $destinationPath = './upload';

        if(!file_exists($destinationPath)){
            mkdir($destinationPath, 0777, true);
            chmod($destinationPath,0777);//加一个权限
        }

        $extension = $file->getClientOriginalExtension();
        $fileName = str_random(10). '.' .$extension;
        $file->move($destinationPath, $fileName);

        $data = self::readExcel("$destinationPath/$fileName", 5);

        $db = \MyDB::getInstance();

//        print_r($data);

        foreach ($data as $row){
            $id = $row[0];
            $content = $row[1];
            $reply1 = $row[2];
            $department = $row[3];
            $type = $row[4];

            $reply = [
                'content' => $reply1,
            ];

            $reply = [$reply];
            $db->update('tickets', [
                'reply' => json_encode($reply, JSON_UNESCAPED_UNICODE),
            ], "id=$id", []);
        }

//        return view('towers.ticket_mgmr', [
//            'tickets' => [],
//            'sid' => $currentUser['sid'],
//        ]);
        return redirect('user/ticket_mgmr.html');

//        return "dd";
    }

    public function ticketInfo(Request $request){
        $currentUser = \MyUtils::getCurrentUser($request);
        $id = $request->input('id', 0);
        if($id == 0) echo "无效id";
        $ticket = \MyDB::getInstance()->findOne("select * from tickets where id = :id", ['id' => $id]);
        $replys = json_decode($ticket['reply'], true);
        return view('towers.ticket_info', [
            'ticket' => $ticket,
            'replys' => $replys,
            'sid' => $currentUser['sid'],
        ]);
    }

    public function pageReply(Request $request){
        $currentUser = \MyUtils::getCurrentUser($request);
        $id = $request->input('id', 0);
        return view('towers.add_reply', [
            'id' => $id,
        ]);
    }

    public function reply(Request $request){
        $currentUser = \MyUtils::getCurrentUser($request);
        $id = $request->input('id', 0);
        $content = $request->input('content', 0);

        $ticket = \MyDB::getInstance()->findOne("select * from tickets where id = :id", ['id' => $id]);
        $replys = json_decode($ticket['reply'], true);
        if(count($replys) == 0){
            $replys = [];
        }

        $replys = [];  //加这句表示回复不可追加，只能覆盖

        $replys[] = [
            'content' => $content,
        ];

        \MyDB::getInstance()->update("tickets", [
            'reply' => json_encode($replys),
        ], "id=$id", []);
//
        return redirect('user/ticket_mgmr.html');
    }




    /**
     * @param $dir  .  不带/
     * @param $file  xx不带后缀 xsls
     * @param $data   ['a' => 1, 'b' => 值]
     * @param $headers ['租金' => 'a', '日期' => 'b']
     */
    public static function writeExcel($dir, $file, $data, $headers){
        $objPHPExcel = new PHPExcel();

        $objPHPExcel->getProperties()->setCreator("理想三旬")
            ->setLastModifiedBy("理想三旬");
//            ->setTitle("粗数据")
//            ->setSubject("文档主题")
//            ->setDescription("文档的描述信息")
//            ->setKeywords("设置文档关键词")
//            ->setCategory("设置文档的分类");

        //定义所有列
        $columns = [
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
            'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM',
            'AN', 'AO', 'AP', 'AQ', 'AR',  'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
        ];

        //设置header
        $row = 1;
        $column = -1;
        foreach (array_keys($headers) as $header){
            $column++;
//            echo $columns[$index] . "$row<br/>";
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue($columns[$column] . "$row", $header);
        }


        //设置每一行
        $row = 1;

        foreach ($data as $item){

            $row++;
            $column = -1;
            foreach ($headers as $header => $value){
                $column++;
                $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue($columns[$column] . "$row", $item[$value])
                ;
                $objPHPExcel->getActiveSheet()->getRowDimension($row)->setRowHeight(-1);
            }

        }


        // 重命名工作sheet
        $objPHPExcel->getActiveSheet()->setTitle('sheet1');
        // 设置第一个sheet为工作的sheet
        $objPHPExcel->setActiveSheetIndex(0);
        // 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save("$dir/$file.xlsx");
    }


    public static function readExcel($file, $row_size){
//        $excelfilename = '/Users/cowthan/Desktop/ws/www/contractor/public/contractor.xls';
//        $objPHPExcel = new PHPExcel();
        $objPHPExcel = PHPExcel_IOFactory::load($file);

        //获取excel里面的数据
        $objworkSheet=$objPHPExcel->getSheet(0)->toArray();

        $titleCount = 1;

        $headers = $objworkSheet[0];

        $data = [];
        for ($i = $titleCount; $i < Lang2::count($objworkSheet); $i++){
            $row = $objworkSheet[$i];

            $data[] = $row;
        }


        return $data;

//        echo json_encode($objworkSheet,JSON_UNESCAPED_UNICODE);
    }
}

?>